<template>

  <basic-container>
    <div class="search_form">
      <el-form ref="form" :model="queryForm" label-width="100px" @submit.native.prevent>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="客户:">
              <el-select id="id-business-receivable-queryForm-customerId" v-model="queryForm.customerId" clearable
                         filterable size="mini" placeholder="请选择客户名称"
                         style="width: 100%"
                         ref="customerId" @change="searchForm">
                <el-option v-for="(item,index) in billingCustomerList"
                           :key="index" :label="item.name" :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="账单月份:">
              <el-date-picker
                v-model="queryForm.occurMonth"
                style="width: 90%"
                type="month"
                size="mini"
                value-format="yyyy-MM"
                @change="searchForm">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="最后开票日期:">
              <el-date-picker
                v-model="this.invoiceDate"
                style="width: 90%"
                type="daterange"
                size="mini"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col span="4" style="min-width: 160px;display:flex;justify-content:flex-end;float: right">
            <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
              <el-button :class="upIcon" class="search-circle" @click="unfoldIcon"
                         style="margin-right: 10px"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="重置" placement="top">
              <el-button id="id-business-customer-emptyForm" :class="emptyIcon" class="search-circle"
                         @click="emptyForm"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button id="id-business-customer-searchForm" ype="primary" icon="el-icon-search" size="small"
                         @click="searchForm" style="margin-right: 0">
                搜索
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <beetles-table :option="option"
                   :table-loading="loading"
                   :view-name="'billingProgress'"
                   :data="data"
                   :page.sync="page"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   :row-class-name-rollback="getRowClassName"
                   ref="crud"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad">
      <template slot-scope="{row}" slot="status">
        <el-select v-model="row.status"
                   size="mini"
                   @change="changeStatus(row)">
          <el-option label="停止" :value="0"></el-option>
          <el-option label="活跃" :value="1"></el-option>
        </el-select>
      </template>

      <template slot-scope="{row}" slot="proceedStatus">
        <el-select v-model="row.proceedStatus"
                   size="mini"
                   @change="changeStatus(row)">
          <el-option label="未处理" :value="0"></el-option>
          <el-option label="已处理" :value="1"></el-option>
        </el-select>
      </template>

      <template slot-scope="{row}" slot="paymentType">
        <span>{{getPaymentType(row.paymentType)}}</span>
      </template>

      <template slot="menuLeft">
        <el-button id="id-finance-billingProgress-handleExport"
                   type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   :disabled="!(selectionList.length > 0)"
                   v-if="permissionList.excelBtn"
                   @click="handleExport">导 出
        </el-button>
      </template>
      <template slot-scope="{type,disabled}" slot="offerLabel">
        <span>offer ( {{ offerList.length }} )</span>
      </template>
      <template slot-scope="{row}" slot="orderListTitleForm">
        <div style="margin-right: -100%">
        </div>
      </template>
      <template slot-scope="{row}" slot="orderListForm">
        <div style="margin-left: -50px;margin-right: -100%">
          <customer-offer-list :customerId="row.id"></customer-offer-list>
        </div>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-tooltip content="查看" placement="top">
          <el-button size="small" icon="el-icon-view" type="text" @click="rowView(scope.row,scope.index)"
                     :disabled="!(permissionList.viewBtn)"></el-button>
        </el-tooltip>
      </template>
    </beetles-table>
    <el-drawer size="60%" :title="drawerTitle" :visible.sync="drawerVisible" :modal-append-to-body="false"
               style="width:100%;" :close-on-press-escape="false" :wrapperClosable="false"
               :close-on-click-modal="false" :before-close="handlerDrawerClose" :append-to-body="true">
      <el-form ref="form" :model="form" label-width="100px" style="width: 90%;margin: 0 auto" :rules="rules">
        <el-row :gutter="20" style="display: flex;flex-wrap: wrap">
          <el-col :span="item.span || 12" v-for="(item,index) in option.column" :key="index" v-if="drawerTitle === '查 看'
          ? (item.viewDisplay === false ? false : true) : drawerTitle ==='新 增' ? (item.addDisplay === false ? false : true):
          (item.editDisplay === false ? false : true)">
            <el-form-item :label="item.label" :prop="item.prop">
              <el-select clearable :disabled="drawerTitle === '查 看' || (item.prop === 'level' && !roles.admin)"
                         style="width: 100%" size="mini"
                         v-if="item.type === 'select'" v-model="form[item.prop]">
                <el-option v-for="it in item.dicData" :key="item.props ? it[item.props.value] : it.value"
                           :label="item.props ? it[item.props.label] : it.label"
                           :value="item.props ? it[item.props.value] : it.value"
                           ></el-option>
              </el-select>
              <el-switch v-if="item.type === 'switch'" v-model="form[item.prop]" :active-value='1' :inactive-value='0'
                         :disabled="drawerTitle === '查 看'">
              </el-switch>
              <span v-if="item.type === 'text'">{{curBriefName}}</span>
              <el-input v-if="item.type === 'textarea'" type="textarea" :disabled="drawerTitle === '查 看'" size="mini"
                        v-model="form[item.prop]" :autosize="{ minRows: 5 }" maxlength="500" show-word-limit></el-input>
              <el-input maxlength="100" :disabled="drawerTitle === '查 看'" v-if="item.type === 'input' || !item.type"
                        size="mini"
                        v-model="form[item.prop]"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="drawerTitle !== '查 看'" style="display: flex;justify-content: flex-end">
          <el-button size="mini" type="primary" icon="el-icon-circle-check" @click="handleForm">保存</el-button>
          <el-button size="mini" icon="el-icon-circle-close" @click="handlerDrawerClose">取消</el-button>
        </div>
      </el-form>
    </el-drawer>
    <div id="downloadExcel"></div>
  </basic-container>
</template>

<script>
import {
  getBillingProgressList,
  getBillingCustomers
} from "@/api/finance/billingProgress";
import {deepClone, exportExcel} from "@/util/util";
import {mapGetters} from "vuex";
import BeetlesTable from "@/components/basic-components/beetles-table";
import {alterStatus} from "../../api/business/customer";
import {getProductName} from "../../api/business/appManager";
import {getReceivableCustomers} from "@/api/finance/receivable";

export default {
  components: {
    BeetlesTable,
  },
  data() {
    return {
      index: 0,
      editData: [],
      invoiceDate: [],
      productNameList: [],
      billingCustomerList: [],
      upIcon: 'el-icon-arrow-down',
      searchConceal: false,
      rowStatus: [{label: "活跃", value: "1"}, {label: "停止", value: "0"}],
      rules: {},
      form: {},
      createTime: [],
      queryForm: {
        customerId: '',
        occurMonth: '',
        startOpenInvoiceTime: '',
        endOpenInvoiceTime: ''
      },
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      emptyIcon: 'el-icon-delete',
      drawerTitle: '',
      drawerVisible: false,
      managerList: [],
      selectionList: [],
      createUserList: [],
      curBriefName: "",
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 120,
        selection: true,
        dialogClickModal: false,
        dialogWidth: 1200,
        column: [
          {
            label: "客户",
            type: 'select',
            prop: "customerName",
            overHidden: true,
            fixed: true,
          },
          {
            label: "账单月份",
            prop: "occurMonth",
            filterable: true,
            type: 'datemonth',
            valueFormat: 'yyyy-MM-dd',
            viewDisplay: true,
          },
          {
            label: "成本",
            prop: "cost",
            viewDisplay: true,
          },
          {
            label: "开票金额($)",
            prop: "billingAmount",
            viewDisplay: true,
          },
          {
            label: "未开金额($)",
            prop: "balance",
            viewDisplay: true,
          },
          {
            label: "最后一次开票日期",
            prop: "lastInvoiceDate",
            filterable: true,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "更新人",
            prop: "createTime",
            addDisplay: false,
            editDisplay: false,
          },
        ]
      },
      data: [],
      currOpRowId: '',
      offerList: [],

    };
  },
  computed: {
    ...mapGetters(["permission", "roles", "userInfo"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.billing_progress),
        excelBtn: this.vaildData(this.permission.billing_progress, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch: {
    'form.customerName': {
      handler(val) {
        this.curBriefName = this.option.column[1].dicData.find(item => item.key === val).data
      }
    }
  },
  created() {
    this.init();
    this.buildSearch();
  },
  methods: {
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    productNameString(productName) {
      let nameList = []
      if (productName !== '') {
        nameList = productName.split(",")
      }
      return nameList
    },
    statusTableList() {
      return [
        {label: '活跃', value: 1},
        {label: '停止', value: 0}
      ]
    },
    /**
     * 新增
     */
    handleAdd() {
      this.optionRules()
      this.form = {
        phone: '',
        email: '',
      }
      this.drawerTitle = '新 增';
      this.drawerVisible = true;
    },
    /**
     * 查看
     */
    rowView(row) {
      this.form = row;
      this.beforeOpen();
      this.drawerTitle = '查 看';
      this.drawerVisible = true;
    },
    /**
     * 编辑
     */
    rowEdit(row) {
      this.rules = {}
      this.form = deepClone(row);
      this.beforeOpen();
      this.drawerTitle = '编 辑';
      this.drawerVisible = true;
      this.optionRules()
    },
    /**
     * 新增/编辑判断条件
     */
    optionRules() {
      this.option.column.map(item => {
        if (item.rules) {
          let rule = {[item.prop]: item.rules}
          this.rules = Object.assign(this.rules, rule)
        }
      })
    },
    init() {
      getBillingCustomers().then(res => {
        this.billingCustomerList = res.data.data
      })
    },
    getPaymentType(id) {
      if (id == 0) return "预付";
      if (id == 1) return "后付";
      if (id == 2) return "退税";
      if (id == 3) return "退款";
      if (id == 4) return "充值";
    },
    buildSearch() {
      if (this.invoiceDate === '' || this.invoiceDate === null){
        this.queryForm.startOpenInvoiceTime = ''
        this.queryForm.endOpenInvoiceTime = ''
      }else if (this.invoiceDate !== ''){
        this.queryForm.startOpenInvoiceTime = this.createTime[0]
        this.queryForm.endOpenInvoiceTime = this.createTime[1]
      }
      this.query = {...this.queryForm};
    },
    searchForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buildSearch();
          this.page.currentPage = 1
          this.onLoad(this.page)
        }
      });
    },
    /**
     * 关闭抽屉
     */
    handlerDrawerClose() {
      this.drawerVisible = false;
      // this.refreshChange()
    },
    //清楚按钮函数
    emptyForm() {
      this.queryForm = {
        name: '',
        createUser: '',
        level: '',
        status: '',
        productName: '',
        phone: '',
        address: '',
        startDate: '',
        endDate: ''
      }
      this.createTime = []
      this.searchForm();
    },
    handleForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.drawerTitle === '新 增') {
            this.rowSave();
          } else {
            this.rowUpdate();
          }
        }
      });
    },
    async beforeOpen(type) {
      if (["edit", "view"].includes(type)) {
        this.currOpRowId = this.form.id;
        // await getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
    },
    searchReset() {
      this.emptyForm();
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getBillingProgressList(page.currentPage, page.pageSize, Object.assign({}, params, this.query))
          .then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleExportWordInvoice() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择一条数据");
        return;
      }
    },
    handleExportPdfInvoice() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择一条数据");
        return;
      }
    },
    handleExport() {
      this.$confirm("是否导出客户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let tableData = {
          title: null,
          headers: [],
          rowList: [],
          bottom: [],
        };
        tableData.headers.push({data: '公司名称', style: 'text-align: right;'});
        tableData.headers.push({data: '销售经理', style: 'text-align: right;'});
        tableData.headers.push({data: '客户经理', style: 'text-align: right;'});
        tableData.headers.push({data: '客户等级', style: 'text-align: right;'});
        tableData.headers.push({data: '状态', style: 'text-align: right;'});
        tableData.headers.push({data: '产品名称', style: 'text-align: right;'});
        tableData.headers.push({data: '联系电话', style: 'text-align: right;'});
        tableData.headers.push({data: '公司邮箱', style: 'text-align: right;'});
        tableData.headers.push({data: '地址', style: 'text-align: right;'});
        tableData.headers.push({data: '备注', style: 'text-align: right;'});

        this.selectionList.forEach(row => {
          let colList = [];
          colList.push({data: row.name, style: 'text-align: right;'});
          colList.push({data: row.level, style: 'text-align: right;'});
          colList.push({data: (row.status === 0) ? '停止' : '活跃', style: 'text-align: right;'});
          colList.push({data: row.productName, style: 'text-align: right;'});
          colList.push({data: row.phone, style: 'text-align: right;'});
          colList.push({data: row.email, style: 'text-align: right;'});
          colList.push({data: row.address, style: 'text-align: right;'});
          colList.push({data: row.remark, style: 'text-align: right;'});
          tableData.rowList.push(colList);
        });
        exportExcel('downloadExcel', tableData.title, tableData.headers, tableData.rowList, tableData.bottom, '客户数据表.xls');
      });
    },
    getRowClassName({row}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
  }
};
</script>

<style lang="scss">
.search_form {
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
}

.view-offer-table {
  margin-top: 40px;

  /deep/ .el-table td, .el-table th {
    padding: 9px 0;
  }
}
</style>
<style lang="scss" scoped>
/deep/ .current-op-row {
  background-color: #f5dab1;
}

/deep/ .el-input__inner {
  text-overflow: ellipsis;
}
</style>
